<template>
  <article class="sign_view" id="content">
    <section v-if="!this.$store.state.login">
      <button @click="enableLogin">登录</button>
      <button @click="enableRegister">注册</button>
      <Login :client_id="this.client_id" :pic_src="this.check_pic" v-show="mode=='login'" />
      <Register :client_id="this.client_id" :pic_src="this.check_pic" v-show="mode=='regis'" />
    </section>
    <section v-if="this.$store.state.login">
      <UserInfo />
      <PwdChange />
    </section>
    <p id="tip" v-show="request_time>9">验证码请求失败，请稍后获取</p>
  </article>
</template>

<script>
// @ is an alias to /src
import "@/assets/css/index.css";
import axios from "axios";
import Register from "@/components/Register.vue";
import Login from "@/components/Login.vue";
import UserInfo from "@/components/UserInfo.vue";
import PwdChange from "@/components/PwdChange.vue";
import { getLocalID } from "@/assets/userState";

export default {
  name: 'Sign',
  components: { Register,Login,UserInfo,PwdChange },
  data() {
    return {
      check_pic:'',
      client_id:'',
      request_time:0,
      mode:'login',
      info : this.$route.query.res
    }
  },
  methods: {
    markId(){
      // 获取本地id
      this.client_id = getLocalID('clientId');
      // 未登录状态下获取验证码
      if (!this.$store.state.login) {
        this.getPic();
      }
      // localStorage.setItem('clientId',this.client_id);
    },
    getPic(){
      const pic_require = axios.create({
        baseURL: "",
      });
      var cli_info = {
        clientid: this.client_id,
        // timestamp: new Date().toLocaleString()
      };
      pic_require({
        url: "/apiPic",
        method:'POST',
        data: cli_info
      }).catch(function (error) {
        if (error.response) {
          console.log('验证码请求失败',error.response.status);
        } else {
          console.log('Error', error.message);
          console.log(error.config);
        }
      }).then((res) => {
        if (!res){//未收到数据，跳出函数
          return
        }
        if (res['data']=='resetID') {
          console.log('未收到数据');
          if (this.request_time < 10) {
            this.request_time++
            localStorage.removeItem('clientId');
            setTimeout(() => {
              this.markId(); // 重置id
            }, 300);
          }
          // var cate_list = res["data"]['cate_list'];
        }else{
          // 存储验证码
          // console.log(res, "res", isNaN(res));
          var data = res['data'];
          this.check_pic = 'data:;base64,'+data;
        }
      });
    },
    alertTip(){
      if (this.info) {
        window.alert(this.info);
      }
    },
    enableLogin(){
      this.mode = 'login';
    },
    enableRegister(){
      this.mode = 'regis';
    },
  },
  created() {
    this.markId();
  },
  mounted() {
    this.alertTip();
  },
}
</script>

<style scoped>
#tip{
  color: red;
}
</style>